import axios from 'axios'
import Cache from '../cache'

const instance = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 5000
})

instance.interceptors.request.use(config => {
  // 请求拦截要处理的内容
  console.log('config', config)
  const user = Cache.get('USER') || {token: ''}
  config.headers = {
    authorization: `Bearer ${user.token}`
  }
  return config
}, err => {
  console.log('请求失败', err)
})

// 相应拦截器
instance.interceptors.response.use(res => {
  // 响应拦截要处理的内容
  return res
}, err => {
  console.log('响应失败', err)
})

/**
 * 封装 http 请求的方法
 * @param option 配置对象，属性包括
 * method 请求方法
 * path 请求接口地址
 * params 请求参数
 */
async function http(option = {}) {
  let result = null
  const method = option.method.toLocaleString()
  switch (method) {
    case 'get':
    case 'delete':
      await instance[method](
        option.path,
        {
          params: option.params
        }
      )
        .then(rel => {
          result = rel
        })
        .catch(err => {
          result = err
        })
      break
    case 'post':
    case 'put':
      await instance[method](
        option.path,
        option.params
      )
        .then(rel => {
          result = rel
        })
        .catch(err => {
          result = err
        })
      break
  }
  return result
}

export default http
